<template>
  <div class="grid-container">
    <div ref="chartRef" class="chart-container"></div>
    <div class="controls">
      <h3>网格控制</h3>
      <div class="control-group">
        <label>高亮网格位置：</label>
        <div class="input-group">
          <label for="row">行:</label>
          <input
            type="number"
            id="row"
            v-model.number="highlightRow"
            min="0"
            max="9"
          />
          <label for="col">列:</label>
          <input
            type="number"
            id="col"
            v-model.number="highlightCol"
            min="0"
            max="9"
          />
          <button @click="updateHighlight">应用</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import * as echarts from "echarts";

// 图表引用
const chartRef = ref(null);
let chart = null;

// 网格配置
const gridSize = 10; // 10x10网格
const highlightRow = ref(2); // 默认高亮行
const highlightCol = ref(3); // 默认高亮列

// 经纬度范围 - 可以根据实际需求调整
const lonRange = [110, 120]; // 经度范围
const latRange = [20, 30]; // 纬度范围

// 初始化图表
const initChart = () => {
  // 销毁已有图表实例
  if (chart) {
    chart.dispose();
  }

  // 创建新图表实例
  chart = echarts.init(chartRef.value);

  // 计算网格步长
  const lonStep = (lonRange[1] - lonRange[0]) / gridSize;
  const latStep = (latRange[1] - latRange[0]) / gridSize;

  // 生成网格线数据
  const gridLines = [];

  // 绘制垂直线（经度线）
  for (let i = 0; i <= gridSize; i++) {
    const lon = lonRange[0] + i * lonStep;
    gridLines.push([
      [lon, latRange[0]],
      [lon, latRange[1]],
    ]);
  }

  // 绘制水平线（纬度线）
  for (let i = 0; i <= gridSize; i++) {
    const lat = latRange[0] + i * latStep;
    gridLines.push([
      [lonRange[0], lat],
      [lonRange[1], lat],
    ]);
  }

  // 生成高亮区域数据
  const highlightAreas = [];
  // 计算指定网格的四个顶点
  const row = highlightRow.value;
  const col = highlightCol.value;

  const areaCoordinates = [
    [lonRange[0] + col * lonStep, latRange[0] + row * latStep],
    [lonRange[0] + (col + 1) * lonStep, latRange[0] + row * latStep],
    [lonRange[0] + (col + 1) * lonStep, latRange[0] + (row + 1) * latStep],
    [lonRange[0] + col * lonStep, latRange[0] + (row + 1) * latStep],
  ];

  highlightAreas.push({
    name: `网格 (${row}, ${col})`,
    value: [
      (areaCoordinates[0][0] + areaCoordinates[2][0]) / 2,
      (areaCoordinates[0][1] + areaCoordinates[2][1]) / 2,
    ],
    coords: areaCoordinates,
  });

  // ECharts 配置项
  const option = {
    tooltip: {
      trigger: "item",
      formatter: () => {
        return `网格位置: 行 ${highlightRow.value}, 列 ${highlightCol.value}`;
      },
    },
    // 笛卡尔坐标系
    xAxis: {
      type: "value",
      name: "经度",
      min: lonRange[0],
      max: lonRange[1],
      axisLine: { show: true },
    },
    yAxis: {
      type: "value",
      name: "纬度",
      min: latRange[0],
      max: latRange[1],
      axisLine: { show: true },
    },
    series: [
      // 网格线系列
      {
        type: "lines",
        coordinateSystem: "cartesian2d",
        data: gridLines.map((line) => ({
          coords: line,
        })),
        lineStyle: {
          color: "#999",
          width: 1,
        },
        symbol: ["none", "none"],
      },
      // 高亮区域系列 - 使用自定义系列确保填充效果
      {
        type: "custom",
        coordinateSystem: "cartesian2d",
        renderItem: (params, api) => {
          // 转换坐标到画布坐标
          const points = highlightAreas[0].coords.map((coord) =>
            api.coord([coord[0], coord[1]])
          );

          return {
            type: "polygon",
            shape: {
              points: echarts.graphic.clipPointsByRect(points, {
                x: params.coordSys.x,
                y: params.coordSys.y,
                width: params.coordSys.width,
                height: params.coordSys.height,
              }),
            },
            style: api.style({
              fill: "red",
              stroke: "#000",
              lineWidth: 2,
              opacity: 0.7,
            }),
          };
        },
        data: highlightAreas,
      },
    ],
  };

  // 设置图表配置
  chart.setOption(option);
};

// 更新高亮网格
const updateHighlight = () => {
  // 确保值在有效范围内
  if (highlightRow.value < 0) highlightRow.value = 0;
  if (highlightRow.value >= gridSize) highlightRow.value = gridSize - 1;
  if (highlightCol.value < 0) highlightCol.value = 0;
  if (highlightCol.value >= gridSize) highlightCol.value = gridSize - 1;

  // 重新绘制图表
  initChart();
};

// 监听窗口大小变化，调整图表尺寸
const handleResize = () => {
  if (chart) {
    chart.resize();
  }
};

// 组件挂载时初始化
onMounted(() => {
  initChart();
  window.addEventListener("resize", handleResize);
});

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  if (chart) {
    chart.dispose();
    chart = null;
  }
});
</script>

<style scoped>
.grid-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.chart-container {
  flex: 1;
  width: 100%;
  background-color: #fff;
}

.controls {
  padding: 16px;
  background-color: #f5f5f5;
  border-top: 1px solid #e0e0e0;
}

.control-group {
  margin-top: 8px;
}

.input-group {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-top: 8px;
}

input {
  width: 60px;
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 6px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #359e75;
}
</style>
